import { getButtonListFn, getRequestUrlListFn } from './getMenuOptionList';

import { isString } from '@/utils/is';

import { renderSvg } from '@/utils/index';

import config from '@/config';

const { VUE_APP_SYSTEM_PREFIX, VUE_APP_NAME } = config;

export const setMenuFn = (
  menus: any[] = [],
  authCode = `${VUE_APP_SYSTEM_PREFIX}-${VUE_APP_NAME}`,
  moduleName = VUE_APP_NAME
): [] => {
  // 组装路由数据
  const routers: any = [];

  for (const item of menus) {
    const { name = '', children = [], meta = {} }: { name: string; children: []; meta: any } = item;

    let resourceCode = authCode;

    if (name) {
      const lowerName = `${name.replace(name.charAt(0), name.substring(0, 1).toLowerCase())}`;

      const newButton: any = [];

      const { icon = null, activeMenu = null, hidden = null } = meta;

      let newIcon = icon;

      if (isString(newIcon)) {
        newIcon = renderSvg(newIcon);
      }

      if (resourceCode !== `${VUE_APP_SYSTEM_PREFIX}-${lowerName}`) {
        resourceCode = `${authCode}-${lowerName}`;
      }

      for (const bItem of getButtonListFn(lowerName)) {
        const newBitem = JSON.parse(JSON.stringify(bItem));

        newBitem.name = `${resourceCode}-${newBitem.name}`;

        newButton.push(newBitem as any);
      }

      // todo

      // item.meta = { ...meta, authCode: resourceCode, button: [], requestUrl: getrequestUrlListFn(lowerName), moduleName };

      item.meta = {
        ...meta,
        authCode: resourceCode,
        button: newButton,
        requestUrl: getRequestUrlListFn(lowerName),
        moduleName,
        icon: newIcon,
        hidden: hidden || activeMenu ? true : false,
      };
    }

    if (children.length) {
      item.children = setMenuFn(children, resourceCode, moduleName);
    }

    routers.push(item as any);
  }

  return routers;
};
